package com.mmall.util;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mmall.exception.ParamException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

/**
 * @Author wangtengyu
 * @Create 2018-03-06-14:32
 */
public class BeanValidatorUtil {
    //创建校验工厂
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    //封装校验方法 校验单个实体对象
    public static <T> Map<String, String> validateObject(T object, Class... groups) {
        //获得校验器
        Validator validator = validatorFactory.getValidator();

        Set validatorResult = validator.validate(object,groups);
        if (validatorResult.isEmpty()){
            return Collections.emptyMap();
        }else {
            LinkedHashMap errors= Maps.newLinkedHashMap();
            Iterator iterator=validatorResult.iterator();
            while (iterator.hasNext()){
                ConstraintViolation constraintViolation= (ConstraintViolation) iterator.next();
                errors.put(constraintViolation.getPropertyPath().toString(),constraintViolation.getMessage());
            }
            return errors;
        }
    }

    //封装校验方法 校验集合对象
    public static Map<String,String> validateList(Collection<?> collection){
        Map errors= Maps.newLinkedHashMap();

        //如果没有对象，返回一个空集合
        if (CollectionUtils.isEmpty(collection)){
            return Collections.emptyMap();
        }
        //不是空集合
        Iterator iterator=collection.iterator();
        while (iterator.hasNext()){
            Object object=iterator.next();
            Map error=validateObject(object,new Class[0]);
            Set<Map.Entry> entrySet=error.entrySet();
            for(Map.Entry entry: entrySet){
                errors.put(entry.getKey(),entry.getValue());
            }
        }
        return errors;
    }

    //根据情况选择使用校验单个对象还是集合对象
    public static Map<String,String> validate(Object first,Object... objects){
        if(objects!=null&&objects.length>0){
            return validateList(Lists.asList(first,objects));
        }else{
            return validateObject(first);
        }
    }

    //提供检查方法
    public static void check(Object param)throws ParamException{
        Map<String,String> map=validate(param);
        if(MapUtils.isNotEmpty(map)){
            throw new ParamException(map.toString());
        }
    }

}
